<template>
  <view class="container">

    <!-- 动态表单区 -->
    <view class="form-container">
      <!-- 数码电子 -->
      <view  class="form-section">
		  <view class="form-item">
		    <text class="label">商品图片</text>
		    <view class="media-uploader">
		          <view class="upload-tips">添加图片或视频（最多9个）</view>
		          
		          <view class="media-list">
		            <!-- 已上传的媒体项 -->
		            <view 
		              class="media-item" 
		              v-for="(item, index) in mediaList" 
		              :key="index"
		            >
		              <image 
		                v-if="item.type === 'image'" 
		                class="media-preview" 
		                :src="item.url" 
		                mode="aspectFill"
		              ></image>
		              <video 
		                v-if="item.type === 'video'" 
		                class="media-preview" 
		                :src="item.url" 
		    			show-bottom-progress="false"
		    			show-center-play-btn="false"
		    			show-fullscreen-btn="false"
		                controls
		              ></video>
		              <view class="delete-btn" @click="removeMedia(index)">
		                <uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
		              </view>
		            </view>
		            
		            <!-- 上传按钮 -->
		            <view 
		              class="upload-btn" 
		              v-if="mediaList.length < 9"
		              @click="showMediaPicker"
		            >
		              <uni-icons type="plusempty" size="32" color="#999"></uni-icons>
		            </view>
		          </view>
		        </view>
		  </view>
        <view class="form-item">
          <text class="label">商品名称</text>
          <input v-model="digitalForm.title" placeholder="请输入" />
        </view>
		<view class="form-item">
		  <text class="label">物品分类</text>
		   <picker
				mode="selector" 
				:range="categories" 
				:value="currentCategory" 
				@change="onCollegeChange"
		  >
			<view class="picker-view">
			  {{ categories[currentCategory] || '请选择物品分类' }}
			</view>
		  </picker>
		</view>
        <view class="form-item">
          <text class="label">商品价格</text>
          <input v-model="digitalForm.price" placeholder="请输入" />
        </view>
       
		<view class="form-item">
		  <text class="label">详细描述</text>
		  <textarea 
		    v-model="digitalForm.description" 
		    placeholder="请描述物品细节"
		    auto-height
		  />
		</view>

        <button @click="submitDigital" class="submit-btn">立即发布</button>
      </view>

    </view>
	
	<!-- 媒体选择器 -->
	<uni-popup ref="mediaPicker" type="bottom">
	  <view class="media-picker-popup">
	    <view class="popup-title">选择媒体类型</view>
	    <view class="popup-options">
	      <view class="option-item" @click="chooseImage">
	        <uni-icons type="image" size="24" color="#FF5A5F"></uni-icons>
	        <text>图片</text>
	      </view>
	      <view class="option-item" @click="chooseVideo">
	        <uni-icons type="videocam" size="24" color="#FF5A5F"></uni-icons>
	        <text>视频</text>
	      </view>
	    </view>
	    <view class="cancel-btn" @click="closeMediaPicker">取消</view>
	  </view>
	</uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentCategory: '',
      categories: [],
	  mediaList:[],
      digitalForm: {
        title: '',
        description: '',
		price:'',
		images:'',
		category_id:''
      },
      colleges:[],
	  collegeIndex:'',
      dailyCategories: ['家居用品', '个人护理', '学习文具', '体育器材'],
	  category_id:'',
	  lists:[],
	  picUrl:[],
	  videoUrl:[],
	  type:0
    }
  },
  onLoad() {
  	this.getQuery()
	this.getShool()
  },
  methods: {
	async  getShool(){
	  	const res = await this.$api.get('/School/list','',true)
	  	if(res.data.code === 200) {
	  		this.list = res.data.data
	  		res.data.data.forEach(item => {
	  			this.colleges.push(item.school_name)
	  		})
	  	}
	},
	// 显示媒体选择器
	showMediaPicker() {
	  this.$refs.mediaPicker.open()
	},
	
	// 关闭媒体选择器
	closeMediaPicker() {
	  this.$refs.mediaPicker.close()
	},
	
	// 选择图片
	chooseImage() {
	  this.closeMediaPicker()
	  this.type = 0
	  let that = this
	  uni.chooseImage({
	    count: 9 - this.mediaList.length, // 还能选择的数量
	    sizeType: ['compressed'], // 压缩图
	    sourceType: ['album', 'camera'], // 相册和相机
	    success:  (res) => {
	      // 添加到媒体列表
	      res.tempFiles.forEach((file) => {
			  this.$api.uploadFile('/upload/File',file.path).then(response => {
			    this.mediaList.push({
				  type: 'image',
				  url: response.url,
				})
				that.picUrl.push(response.data.url)
			  })
	
	      })
	    }
	  })
	},
	
	// 选择视频
	chooseVideo() {
	  this.type = 1
	  this.closeMediaPicker()
	  let that = this
	  uni.chooseVideo({
	    sourceType: ['album', 'camera'],
	    compressed: true,
	    // maxDuration: 60, // 60秒
	    success: (res) => {
	      // 视频只能选一个，先清空已有的
		  console.log('上传的图片地址',res)
	      this.mediaList = this.mediaList.filter(item => item.type !== 'video')
		  this.$api.uploadFile('/upload/File',res.tempFilePath).then(response => {
		    this.mediaList.push({
		      type: 'video',
		      url: response.url,
		      file: {
		        path: res.tempFilePath,
		        size: res.size,
		        duration: res.duration,
		        width: res.width,
		        height: res.height
		      }
		    })
			that.videoUrl = response.url
		  })
	      // that.$api.uploadFile('/file/upload',res.tempFilePath,'videoUrl/').then((response) => {
	      // 	console.log('上传的图片地址',response)
	      // 	that.videoUrl = response.link
	      // })
	      
	    }
	  })
	},
	
	// 删除媒体
	removeMedia(index) {
	  this.mediaList.splice(index, 1)
	  this.picUrl.splice(index,index)
	  this.videoUrl.splice(index,1)
	},
	onCoChange(e) {
	  this.collegeIndex = e.target.value;
	  this.digitalForm.college = this.colleges[this.collegeIndex];
	},
	onCollegeChange(e) {
	  this.currentCategory = e.target.value;
	  this.category_id = this.lists[this.currentCategory].id
	  console.log('dadadada',this.category_id);
	},
	async  getQuery(){
		const res = await this.$api.get('/GoodsCategory/list','',true)
		  if(res.data.code === 200) {
			  res.data.data.list.forEach(item => {
				  this.categories.push(item.name)
			  })
			this.lists = res.data.data.list
		  }
	},
    switchCategory(type) {
      this.currentCategory = type
      uni.pageScrollTo({ scrollTop: 0 })
    },
    dateChange(e) {
      this.digitalForm.purchaseDate = e.detail.value
    },
    dailyCategoryChange(e) {
      this.dailyForm.category = this.dailyCategories[e.detail.value]
    },
    otherPaymentChange(e) {
      this.digitalForm.radio = e.detail.value
    },
    async submitDigital() {
		this.digitalForm.category_id = this.category_id
		this.digitalForm.type = this.type
      if (!this.digitalForm.title) {
        return uni.showToast({ title: '请填写商品名称', icon: 'none' })
      }
	  if (!this.digitalForm.price) {
	    return uni.showToast({ title: '请填写商品价格', icon: 'none' })
	  }
	  if (!this.digitalForm.description) {
	    return uni.showToast({ title: '请填写商品描述', icon: 'none' })
	  }

	  this.digitalForm.images = JSON.stringify(this.mediaList)
	  if (!this.digitalForm.images) {
	    return uni.showToast({ title: '请上传商品图片', icon: 'none' })
	  }
	  if (!this.digitalForm.category_id) {
	    return uni.showToast({ title: '请选择分类', icon: 'none' })
	  }
	  
	  
	  const res = await this.$api.post('/SecondGoods/send',this.digitalForm,true)
	  if(res.data.code == 200) {
		  uni.showToast({
		  	icon:'none',
			title:res.data.msg
		  })
		  setTimeout(() => {
			  uni.navigateBack({delta:1})
		  },1000)
	  }
      // 提交逻辑...images
    },
    validateISBN(isbn) {
      // ISBN验证逻辑
    }
    // 其他提交方法类似...
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 媒体选择弹出层 */
.media-picker-popup {
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
  color: #333;
}

.popup-options {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.option-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.option-item text {
  margin-top: 15rpx;
}

.cancel-btn {
  text-align: center;
  font-size: 32rpx;
  color: #FF5A5F;
  padding: 30rpx 0;
  border-top: 1rpx solid #eee;
}
/* 媒体上传区 */
.media-uploader {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.upload-tips {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  margin: -10rpx;
}

.media-item, .upload-btn {
  width: 195rpx;
  height: 195rpx;
  margin: 10rpx;
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #f5f5f5;
}

.media-preview {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  right: 10rpx;
  top: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 190rpx;
  height: 190rpx;
  border: 2rpx dashed #ddd;
}


.nav-bar {
  white-space: nowrap;
  padding: 20rpx 0;
  .nav-item {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    width: 160rpx;
    padding: 20rpx;
    transition: all 0.3s;
    &.active {
      .nav-icon {
        transform: scale(1.1);
      }
      .nav-text {
        color: #007AFF;
        font-weight: bold;
      }
    }
  }
  .nav-icon {
    width: 80rpx;
    height: 80rpx;
    transition: transform 0.3s;
  }
  .nav-text {
    font-size: 24rpx;
    margin-top: 10rpx;
    color: #666;
  }
}

.form-container {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 40rpx;
  .label {
    display: block;
    color: #333;
    font-size: 28rpx;
    margin-bottom: 16rpx;
    font-weight: 500;
  }
  input, picker, textarea {
    width: 94%;
    padding: 20rpx;
    border: 2rpx solid #eee;
    border-radius: 12rpx;
    font-size: 28rpx;
  }
  textarea{
	  min-height: 200rpx;
  }
}

.submit-btn {
  background: #007AFF;
  color: white;
  border-radius: 50rpx;
  margin-top: 60rpx;
  font-size: 32rpx;
}

.radio-item {
  margin-right: 40rpx;
  display: inline-flex;
  align-items: center;
}

.rich-editor {
  height: 300rpx;
  border: 2rpx solid #eee;
  padding: 20rpx;
  border-radius: 12rpx;
}
</style>